from DrissionPage import ChromiumPage
from DrissionPage.common import Keys
import csv
import time
import mysql.connector

db = mysql.connector.connect(
    host="localhost",  # MySQL服务器地址
    user="root",   # 用户名
    password="123456",  # 密码
    database="bishe"  # 数据库名称
)

# 创建游标对象，用于执行SQL查询
cursor = db.cursor()


# with open('mouse.csv', mode='w', encoding='UTF-8-sig', newline='') as f:
#
#     csv_writer = csv.DictWriter(f, fieldnames=[
#         '标题',
#         '价格',
#         '评论数',
#         '详情页'
#     ])
#
#     csv_writer.writeheader()

dp = ChromiumPage()

dp.get(
    'https://www.jd.com/?cu=true&utm_source=baidu-search&utm_medium=cpc&utm_campaign=t_262767352_baidusearch&utm_term=158643551949_0_0f17a9e058274d2b9d0f7fd3dc258783')

dp.ele('css:#key').input('鼠标')

dp.ele('css:#key').input(Keys.ENTER)

dp.wait.load_start()  # 等待页面开始加载
time.sleep(2)  # 额外等待2秒，确保页面稳定

for i in range(1, 20):
    time.sleep(2)
    dp.scroll.to_bottom()
    time.sleep(10)
    lis = dp.eles('css:.gl-item')
    # 循环一下提取数据
    for li in lis:
        title = li.ele('css:.p-name a em').text.replace('\n', ' ')
        image = li.ele('css:.p-img a img').attr('src').replace('\n', ' ')
        try:
            price = li.ele('css:.p-price strong i').text.replace('\n', ' ')
        except:
            price = '预售'
        try:
            commit = li.ele('css:.p-commit strong a').text.replace('\n', ' ')
        except:
            commit = '新品上市'
        href = li.ele('css:.p-name a').attr('href').replace('\n', ' ')
        dit = {
            '标题': title,
            '价格': price,
            '评论数': commit,
            '详情页': href,
            '图片': image
        }
        # csv_writer.writerow(dit)
        print(dit)
        try:
            db.start_transaction()
            sql = "INSERT INTO jingdongshubiaoshuju (name, price, number,href,image) VALUES (%s, %s, %s, %s, %s)"
            values = (title, price, commit, href, image)
            cursor.execute(sql, values)
            db.commit()
        except:
            db.rollback()
    #下一页
    lis[0].input(Keys.RIGHT)
    # lis[0].input(Keys.F5)
cursor.close()
db.close()
